import React, {useEffect, useState} from 'react';
import axios from "axios";
import {Link} from "react-router-dom";
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";
import EmptyResultsMessage from "../components/EmptyResultsMessage";
import Pagination from "../components/Pagination";
import * as errmsg from '../constants'

const BasePosts = props => {
    const [loading, setLoading] = useState(true)
    const [posts, setPosts] = useState([])
    const [error, setError] = useState('')
    // 文章总数
    const [count, setCount] = useState(0)
    // 总页码
    const [numPages, setNumPages] = useState(1)
    // 默认显示第一页
    const [page, setPage] = useState(1)
    // queryPage为 url中的?page=3  查询参数
    const {name, url, keyword, queryPage} = props;

    // ComponentDidMount
    // 每次页面挂载后执行
    useEffect(() => {
        // 获取查询字符串?page=1的值
        // 如果没有，page为null
        let page = queryPage
        if (!page)
            page = 1
        else
            page = parseInt(page)

        if (page < 1)
            page = 1

        if (page > numPages)
            page = numPages

        setPage(page)
    }, [setPage, numPages, queryPage])

    useEffect(() => {
        // 查找关键字时的URL有些不一样
        let newUrl = `${url}?page=${page}`
        if (!!keyword && keyword.length > 0)
            newUrl = `${url}?keyword=${keyword}&page=${page}`

        axios.get(newUrl)
            .then(response => {
                setLoading(false)
                setPosts(response.data.results)
                setCount(response.data.count)
                setNumPages(response.data.num_pages)
                setError('')
            })
            .catch(err => {
                setLoading(false)
                setPosts([])
                setCount(0)
                setNumPages(1)
                setError(errmsg.CUSTOM_ERROR_MSG)
            })

    }, [url, page, keyword])

    const postList = (
        posts.map(post => {
            return (
                <p className="list-group-item mb-0 border-0 list-group-item-action" key={post.slug}
                   data-testid={`post-item-${post.id}`}>
                    <span className="text-muted">{post.pub_date} >> </span>
                    <Link className="post-detail-link" key={post.slug} to={`/post/${post.slug}`}>{post.title}</Link>
                </p>
            )
        })
    )

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>
    if (posts.length === 0) return <EmptyResultsMessage/>

    return (
        <div className="col-md-8">
            <h3 className="text-capitalize"># {name}
                <span className="badge bg-secondary rounded-pill ms-1">{count}</span></h3>
            <div className="list-group pl-2 border-0">
                {postList}
            </div>
            <Pagination page={page} numPages={numPages}/>
        </div>
    );
};

export default BasePosts;